package com.ruicar.afs.cloud.admin.controller;
import java.math.BigDecimal;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruicar.afs.cloud.admin.entity.*;
import com.ruicar.afs.cloud.admin.service.*;
import com.ruicar.afs.cloud.common.core.security.annotation.Inner;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.constant.CommonConstants;
import com.ruicar.afs.cloud.common.core.holder.TransRequestContextHolder;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.core.util.TenantUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.security.crypto.password.StandardPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;


@RestController
@AllArgsConstructor
@RequestMapping("/tenant")
@Api(value = "tenant", description = "租户信息维护")
public class TenantController {
	private final SysTenantInfoService sysTenantInfoService;

	private final SysDepartmentService departmentService;


	private final SysRoleService sysRoleService;


	private final SysPermissionService sysPermissionService;

	private final SysRolePermissionService sysRolePermissionService;

	private final SysUserService sysUserService;

	private final SysUserRoleService sysUserRoleService;


	@GetMapping("/info/{tenantId}")
	public IResponse<SysTenantInfo> getSysTenantInfo(@PathVariable String tenantId){
		return new IResponse<>(sysTenantInfoService.getTenantInfoByTenantId(tenantId));
	}

	@GetMapping("/page")
	@ApiOperation(value = "获取租户数据")
	public IResponse<Object> listTenantInfo(@RequestParam(value = "tenantStatus",required = false) String tenantStatus,
	                                        @RequestParam(value = "tenantName",required = false) String tenantName,
	                                        @RequestParam(name = "pageNumber") int pageNumber, @RequestParam(name = "pageSize") int pageSize ){
		return new IResponse().setData(sysTenantInfoService.page(new Page(pageNumber, pageSize)
				, Wrappers.<SysTenantInfo>query().lambda()
						.eq(StringUtils.isNotEmpty(tenantStatus), SysTenantInfo::getTenantStatus, tenantStatus)
						.like(StringUtils.isNotEmpty(tenantName), SysTenantInfo::getTenantName, tenantName)));
	}

	@Transactional
	@PostMapping("/save")
	@ApiOperation(value = "保存租户数据")
	@CacheEvict(value = CommonConstants.TENANT_CACHE_KEY_PREFIX, key = "#sysTenantInfo.tenantId")
	public IResponse save(@Valid @RequestBody SysTenantInfo sysTenantInfo){
		if(sysTenantInfo.getId()==null){
			if(sysTenantInfoService.getTenantInfoByTenantId(sysTenantInfo.getTenantId())!=null){
				return IResponse.fail(sysTenantInfo.getTenantId()+"已存在");
			}else{
				try {
					TenantUtil.close();
					sysTenantInfo.setCreateBy(SecurityUtils.getUsername());
					sysTenantInfo.setCreateTime(new Date());
					sysTenantInfoService.save(sysTenantInfo);

					SysDepartment sysDepartment = new SysDepartment();
					sysDepartment.setTitle("总部");
					sysDepartment.setParentId("0");
					sysDepartment.setIsParent(true);
					sysDepartment.setSortOrder(new BigDecimal("0"));
					sysDepartment.setStatus("1");
					sysDepartment.setCreateBy(SecurityUtils.getUsername());
					sysDepartment.setCreateTime(new Date());
					sysDepartment.setTenantId(sysTenantInfo.getTenantId());
					sysDepartment.setDelFlag(CommonConstants.STATUS_NORMAL);
					departmentService.save(sysDepartment);

					SysRole sysRole = new SysRole();
					sysRole.setRoleName("管理员");
					sysRole.setRoleCode("ROLE_ADMIN");
					sysRole.setDsType("1");
					sysRole.setDsScope(String.valueOf(sysDepartment.getId()));
					sysRole.setCreateBy(SecurityUtils.getUsername());
					sysRole.setCreateTime(new Date());
					sysRole.setTenantId(sysTenantInfo.getTenantId());
					sysRole.setDelFlag(CommonConstants.STATUS_NORMAL);

					sysRoleService.save(sysRole);

					sysPermissionService
							.list(Wrappers.<SysPermission>query().lambda().eq(SysPermission::getTenantHideFlag, CommonConstants.STATUS_NORMAL))
							.forEach(sysPermission -> {
								SysRolePermission sysRolePermission = new SysRolePermission();
								sysRolePermission.setRoleId(String.valueOf(sysRole.getId()));
								sysRolePermission.setPermissionId(String.valueOf(sysPermission.getId()));
								sysRolePermissionService.save(sysRolePermission);
							});


					SysUser sysUser = new SysUser();
					sysUser.setUsername("admin");
					sysUser.setUserRealName("管理员");
					sysUser.setPassword(new StandardPasswordEncoder().encode("123456"));
					sysUser.setCreateTime(new Date());
					sysUser.setUpdateTime(new Date());
					sysUser.setDelFlag(CommonConstants.STATUS_NORMAL);
					sysUser.setLockFlag(CommonConstants.STATUS_NORMAL);
					sysUser.setPhone("-");
					sysUser.setUserEmail("-");
					sysUser.setDeptId(sysDepartment.getId());
					sysUser.setTenantId(sysDepartment.getTenantId());

					sysUserService.save(sysUser);

					SysUserRole sysUserRole = new SysUserRole();
					sysUserRole.setUserId(sysUser.getUserId());
					sysUserRole.setRoleId(sysRole.getId());
					sysUserRole.setTenantId(sysTenantInfo.getTenantId());
					sysUserRoleService.save(sysUserRole);
				}finally {
					TenantUtil.open();
				}
			}
		}else{
			if(TransRequestContextHolder.getClientInfo().getTenantId().equalsIgnoreCase(sysTenantInfo.getTenantId())){
				return IResponse.fail("禁止维护自己所属租户信息");
			}
			sysTenantInfo.setUpdateBy(SecurityUtils.getUsername());
			sysTenantInfo.setUpdateTime(new Date());
			sysTenantInfoService.updateById(sysTenantInfo);
		}
		return IResponse.success(Boolean.TRUE).setMsg("操作成功");
	}
}
